//
//  UIImage+SJCategory.m
//  Project With OC
//
//  Created by Jaesun on 16/7/26.
//  Copyright © 2016年 S.J. All rights reserved.
//

#import "UIImage+SJCategory.h"
#import <Photos/Photos.h>
#import <objc/runtime.h>

@implementation UIImage (SJCategory)

/**
 *  把颜色转变为图片
 *
 *  @param color 颜色
 *
 *  @return 图片
 */
+ (instancetype)imageWithColor:(UIColor *)color
{
    // 描述矩形
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    // 开启位图上下文
    UIGraphicsBeginImageContext(rect.size);
    // 获取位图上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    // 使用color演示填充上下文
    CGContextSetFillColorWithColor(context,[color CGColor]);
    // 渲染上下文
    CGContextFillRect(context, rect);
    // 从上下文中获取图片
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    // 结束上下文
    UIGraphicsEndImageContext();
    return theImage;
}

#pragma mark- --------------------------------图片水印-------------------------------
/**
 *  给图片添加有“属性”的文字
 *
 *  @param maskStr       水印文字
 *  @param attributesDic 文字属性
 *  @param rect          水印文字的位置
 *
 *  @return 添加水印文字之后的图片
 */
- (UIImage *) watermarkImageWithString:(NSString *)maskStr WithStringAttributes:(NSDictionary *) attributesDic inRect:(CGRect)rect {

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 40000 // 系统允许的最大版本大于 4.0
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 4.0)
    {
        
        NSLog(@"%@---%d",[[UIDevice currentDevice] systemVersion],__IPHONE_OS_VERSION_MAX_ALLOWED);
        
        UIGraphicsBeginImageContextWithOptions([self size], NO, 0.0); // 0.0 for scale means "scale for device's main screen".
    }
#else
    if ([[[UIDevice currentDevice] systemVersion] floatValue] < 4.0)
    {
        UIGraphicsBeginImageContext([self size]);
    }
#endif
    //原图
    [self drawInRect:CGRectMake(0, 0, self.size.width, self.size.height)];
    //水印文字
    [maskStr drawInRect:rect withAttributes:attributesDic];
    UIImage *newPic = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newPic;
}

/**
 *  给图片添加有“属性”的文字
 *
 *  @param maskStr       水印文字
 *  @param attributesDic 文字属性
 *  @param range         特殊属性文字的范围
 *  @param rect          水印文字的位置
 *
 *  @return 添加水印文字之后的图片
 */
- (UIImage *) watermarkImageWithString:(NSString *)maskStr WithStringAttributes:(NSDictionary *) attributesDic inRange:(NSRange)range inRect:(CGRect)rect {
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:maskStr];
    [attributedStr addAttributes:attributesDic range:range];
    [attributedStr drawInRect:rect];
    [self drawInRect:CGRectMake(0, 0, self.size.width, self.size.height)];
    //水印文字
    [attributedStr drawInRect:rect];
    UIImage *newPic = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newPic;
    
}

/**
 *  给图片添加 水印图片
 *
 *  @param markImage 水印图片
 *  @param rect 添加水印图片的frame
 *
 *  @return 添加完水印图片的图片
 */
- (UIImage *) watermarkImageWithImage:(UIImage*)markImage inRect:(CGRect)rect {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 40000 // 系统允许的最大版本大于 4.0
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 4.0)
    {
        
        NSLog(@"%@---%d",[[UIDevice currentDevice] systemVersion],__IPHONE_OS_VERSION_MAX_ALLOWED);
        
        UIGraphicsBeginImageContextWithOptions([self size], NO, 0.0); // 0.0 for scale means "scale for device's main screen".
    }
#else
    if ([[[UIDevice currentDevice] systemVersion] floatValue] < 4.0)
    {
        UIGraphicsBeginImageContext([self size]);
    }
#endif
    //原图
    [self drawInRect:CGRectMake(0, 0, self.size.width, self.size.height)];
    
    //水印图
    [markImage drawInRect:rect];
    
    UIImage *newPic = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newPic;
}


#pragma mark- --------------------------------图片压缩-------------------------------

/**
 *  压缩图片到指定尺寸，如果压缩后的尺寸宽高比例与图片原来宽高比例不同 “图片会变形”
 *
 *  @param targetSize 指定尺寸
 *
 *  @return 压缩后图片
 */

- (UIImage*) scaleImageToSize:(CGSize)targetSize {
    
    UIImage *sourceImage = self;
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    
    if (CGSizeEqualToSize(imageSize, targetSize) == NO) {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        scaledWidth = width * widthFactor;
        scaledHeight = height * heightFactor;
    }
    
    UIGraphicsBeginImageContext(targetSize); // this will crop
    
    CGRect thumbnailRect = CGRectZero;
    
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width= scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil)
        NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}

/**
 *  按比例压缩图片（尺寸比例）压缩后图片的“尺寸”和“容量”大小都变化
 *
 *  @param scaleRate 压缩比例 如：尺寸为 1024 * 1024 的图片按 0.5 压缩后图片尺寸为 512 * 512
 *
 *  @return 压缩后的图片
 */
- (UIImage *)scaleImageToScaleRate:(CGFloat)scaleRate {
    
    CGFloat scaledFactor = scaleRate; // 压缩比例
    UIImage *sourceImage = self; // 压缩前图片
    UIImage *destinationImage = nil; // 压缩后图片
    CGSize scaledSize = CGSizeZero; // 压缩后图片尺寸
    CGPoint thumbnailPoint = CGPointZero;
    NSData *data = nil;
    
    scaledSize.width = sourceImage.size.width * scaledFactor;
    scaledSize.height = sourceImage.size.height * scaledFactor;
    
    // 重新画图
    UIGraphicsBeginImageContext(scaledSize); // this will crop
    
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width= scaledSize.width;
    thumbnailRect.size.height = scaledSize.height;
    [sourceImage drawInRect:thumbnailRect];
    
    destinationImage = UIGraphicsGetImageFromCurrentImageContext();
    
    if(destinationImage == nil) {
        NSLog(@"could not scale image");
    }
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    
    data = UIImagePNGRepresentation(destinationImage);
    return destinationImage;
}

/**
 *  压缩png格式图片到指定内存大小
 *
 *  @param length 内存大小（单位:byte）
 *
 *  @return 压缩后的图片
 */
- (UIImage *)compassImageToLength:(NSInteger)length {

    UIImage *resultImage = self;
    NSData *imageData = UIImageJPEGRepresentation(resultImage,1.0);
    CGFloat compass = 1.0;
    
    while(imageData.length > length && compass >= 0.1) {
        compass -= 0.1;
        imageData = UIImageJPEGRepresentation(resultImage, compass);
        resultImage = [UIImage imageWithData:imageData];
    }
    return resultImage;
}

/**
 *  压缩png格式图片到指定内存大小
 *
 *  @param length 内存大小（单位:byte）
 *
 *  @return 压缩后的图片
 */
- (UIImage *)scaleImageToLength:(NSInteger)length {
    
    CGFloat scaledFactor = 1;
    UIImage *sourceImage = self; // 压缩前图片
    UIImage *destinationImage = nil; // 压缩后图片
    CGSize scaledSize = CGSizeZero; // 压缩后图片尺寸
    CGPoint thumbnailPoint = CGPointZero;
    NSData *data = UIImagePNGRepresentation(sourceImage);
    
    while ([data length] > length) { // 如果内存大于 length,循环压缩
        
        scaledFactor -= 0.1;
        
        scaledSize.width = sourceImage.size.width * scaledFactor;
        scaledSize.height = sourceImage.size.height * scaledFactor;
        // 重新画图
        UIGraphicsBeginImageContext(scaledSize); // this will crop
        
        CGRect thumbnailRect = CGRectZero;
        thumbnailRect.origin = thumbnailPoint;
        thumbnailRect.size.width= scaledSize.width;
        thumbnailRect.size.height = scaledSize.height;
        [sourceImage drawInRect:thumbnailRect];
        destinationImage = UIGraphicsGetImageFromCurrentImageContext();
        
        if(destinationImage == nil) {
            NSLog(@"could not scale image");
        }
        // pop the context to get back to the default
        UIGraphicsEndImageContext();
        data = UIImagePNGRepresentation(destinationImage);
    }
    return destinationImage;
}

+ (UIImage *)scaleImage:(UIImage *)image toKb:(NSInteger)kb{
    
    if (!image) {
        return image;
    }
    if (kb<1) {
        return image;
    }
    kb*=1024;
    NSData *imageData;
    UIImage *curImage = image;
    
    do {
        imageData = UIImageJPEGRepresentation(curImage, 0.5);
        curImage = [UIImage imageWithData:imageData];
        NSLog(@"当前大小:%fkb",(float)[imageData length] / 1024.0f);
    }
    while ([imageData length] <= kb);
    
    return curImage;
}

/**
 *  1. 压缩图片容量到指定"内存大小" 图片的 “尺寸不变”
 *  2. 压缩是把图片转换为JPEG格式的数据进行压缩，JPEG格式的数据在转换为图片是内存会增加，所以要把压缩后的数据一起保存到字典中返回，使得用于上传到服务器，或保存到本地的数据为最接近我们想要的大小（单位:Byte）
 *
 *  @param length 压缩后图片的最大内存 (单位:Byte)
 *
 *  @return 压缩后的图片
 */
- (NSMutableDictionary *)compressImageToLength:(NSInteger)length {
    
    NSMutableDictionary *imageInfoDic = nil;
    
    CGFloat compression = 1.0f;
    CGFloat maxCompression = 0.1f;
    
    UIImage *sourceImage = self;
    
    NSData *imageData = UIImageJPEGRepresentation(sourceImage, 1.0);
    
    while ([imageData length] > length && compression > maxCompression) {
        
        compression -= 0.1;
        imageData = UIImageJPEGRepresentation(sourceImage, compression);
    }
    
    UIImage *destinationImage = [UIImage imageWithData:imageData];
    
    imageInfoDic = [NSMutableDictionary dictionary];
    
    [imageInfoDic setObject:destinationImage forKey:@"image"];
    
    [imageInfoDic setObject:imageData forKey:@"imageData"];
    
    return imageInfoDic;
}

#pragma mark- ----------------------------------截图---------------------------------

/**
 *  截取一个contentView的内容
 *
 *  @param view 要截图的视图
 */
+ (UIImage *)shotscreenInView:(UIView *)view
{
    if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]){
        UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, [UIScreen mainScreen].scale);
    } else {
        UIGraphicsBeginImageContext(view.bounds.size);
    }
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

/**
 *  截屏
 *
 *  @param window 要截屏的屏幕
 */

+ (UIImage *)shotscreenInWindow:(UIWindow *)window {
   
    if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]){
        UIGraphicsBeginImageContextWithOptions(window.bounds.size, NO, [UIScreen mainScreen].scale);
    } else {
        UIGraphicsBeginImageContext(window.bounds.size);
    }
    [window.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return  image;
}



@end
